package com.finalcial.controller;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.finalcial.service.ApplicationService;

@Controller
@RequestMapping("/upload")
public class UploadFileController {
	@Autowired
	private ApplicationService applicationService;
	/*@RequestMapping(value="/uploadImages" , method = RequestMethod.POST)
	public void webUploadFile(HttpServletRequest request, HttpServletResponse response) {
		//通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		//判断request里面是否有文件上传
		if(multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			//去的request中所有的文件名
			Iterator<String> iter = multiRequest.getFileNames();
			while(iter.hasNext()) {
				//取得当前上传文件
				MultipartFile file = multiRequest.getFile(iter.next());
				if(file != null) {
					//取得当前上传文件名
					String myFileName = file.getOriginalFilename();
					//如果名称不为"",说明该文件存在，否则说明该文件不存在
					if(myFileName.trim() != "") {
						System.out.println(myFileName);
						try {
							//上传路径
							SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
							String ymd = sdf.format(new Date());
							String pat=request.getSession().getServletContext().getRealPath("/images/"+ymd+"/");//获取文件保存路径
							response.setContentType("text/html; charset=UTF-8");
	                        File fileDir=new File(pat);
	                        if (!fileDir.exists()) { //如果不存在 则创建     文件夹
	                            fileDir.mkdirs();    
	                        }
	                        //重命名当前上传文件   文件名+扩展名
	                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
							String fileName =  df.format(new Date())+"_"+new Random().nextInt(1000)+"."
									+ myFileName.substring(myFileName.lastIndexOf(".") + 1).toUpperCase();
	                        String path = pat+fileName;//文件夹+文件名
	                        System.out.println(path);
	                        File localFile = new File(path);
	                        file.transferTo(localFile);
						} catch (IllegalStateException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}*/
	
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	@ResponseBody
	public Map<String ,Object> uploadFile(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String invoiceTypeId = request.getParameter("invoiceTypeId");
		String invoiceTime = request.getParameter("invoiceTime");
		String reimbursementId = request.getParameter("reimbursementId");
		System.out.println(invoiceTypeId);
		System.out.println(invoiceTime);
		System.out.println(reimbursementId);
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> resultSrc = new HashMap<String, Object>();
		
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();//文件集合
		String projectName = request.getContextPath();
		String outStr = "";
		// 文件保存目录路径
		String savePath = request.getSession().getServletContext().getRealPath("/uploadFiles/photo/");
		response.setContentType("text/html; charset=UTF-8");
		// 检查目录
		File uploadDir = new File(savePath);
		if (!uploadDir.isDirectory()) {
			// 如果不存在，创建文件夹
			if (!uploadDir.exists()) {
				uploadDir.mkdirs();
			}
		}
		String dirName = request.getParameter("dir");
		if (dirName == null) {
			dirName = "image";
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		String ymd = sdf.format(new Date());
		savePath += "/" + ymd + "/";
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		// 此处是直接采用Spring的上传
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile mf = entity.getValue();//获得文件对象
			String fileFullname = mf.getOriginalFilename();//获得文件名
			fileFullname = fileFullname.replace('&', 'a');
			fileFullname = fileFullname.replace(',', 'b');
			fileFullname = fileFullname.replace('，', 'c');
			// 扩展名
			String fileExt = fileFullname.substring(fileFullname.lastIndexOf(".") + 1).toLowerCase();//扩展名

			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String filename = df.format(new Date()) + "_"+ new Random().nextInt(1000);//文件名
			String newFileName = filename + "." + fileExt;//文件名+扩展名

			File uploadFile = new File(savePath + newFileName);
			try {
				//spring的文件拷贝
				FileCopyUtils.copy(mf.getBytes(), uploadFile);
				String enclosureSize = uploadFile.length()/1024 + "." + uploadFile.length()%1024;//文件大小保存为kb
				System.out.println("!!"+enclosureSize);
				BigDecimal bd = new BigDecimal(enclosureSize);
				bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);//取小数点后2位
				System.out.println(bd.toString());
				outStr += projectName + "/uploadFiles/photo/" + ymd + "/"+ newFileName;
				applicationService.insertUploadAndMsg(filename, invoiceTime, reimbursementId, Integer.valueOf(invoiceTypeId), outStr, bd.toString());
				System.out.println(outStr);
			} catch (IOException e) {
				result.put("code", 200);
				result.put("msg", "上传失败");
				e.printStackTrace();
			}
		}
		result.put("code", 0);
		result.put("msg", "上传成功");
		resultSrc.put("src", outStr);   
		result.put("data", resultSrc);
		return result;
		// 上传结束
	}
}
